package jwlee.testxml;

import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;

/**
 * Castor一种将java对象和XML自动绑定的开源软件。它可以在java对象、XML文本、SQL数据表以及LDAP目录之间绑定。
 * Castor几乎是JAXB的替代品。
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright:  Copyright (c) 2012</p>
 * <p>Company:  </p>
 * 
 * @author lijwg
 * @date 2012-5-17
 * @version 1.0
 */
public class CastorTester {
	static String path = "c:\\";

	public static void main(String[] args) {
		testMarshaller();
		
//		testUnMarshaller();
	}

	/**
	 * java->XML
	 */
	public static void testMarshaller() {
		try {
			Foo f = new Foo("foo");
			f.setName("mzj");
			f.getAdds().add("zhengzhou");
			f.getAdds().add("beijing");
			f.getMap().put("a", "aaa");
			f.getMap().put("b", "bbb");

			FileWriter writer = new FileWriter(path + "foo.xml");
			Marshaller marshaller = new Marshaller(writer);
			marshaller.setEncoding("GBK");
			marshaller.marshal(f);//
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * XML->java
	 */
	public static void testUnMarshaller() {
		try {
			FileReader reader = new FileReader(path + "foo.xml");
			Foo foo = (Foo) Unmarshaller.unmarshal(Foo.class, reader);
			System.out.println("Name: " + foo.getName());
			System.out.println("Birthday: " + foo.getBirthday());
			for (Object s : foo.getAdds()) {
				System.out.println("Add: " + s.toString());
			}
			for (Object o : foo.getMap().entrySet()) {
				Map.Entry e = (Map.Entry) o;
				System.out.println("Map: " + e.getKey() + "--" + e.getValue());
			}
		} catch (Exception e) {
			System.err.println(e.getMessage());
			e.printStackTrace(System.err);
		}
	}
}

class Foo implements java.io.Serializable {
	String name;
	String birthday;
	List adds = new ArrayList();
	Map map = new HashMap();

	Foo() {
	}

	Foo(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getBirthday() {
		return birthday;
	}

	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}

	public List getAdds() {
		return adds;
	}

	public void setAdds(List adds) {
		this.adds = adds;
	}

	public Map getMap() {
		return map;
	}

	public void setMap(Map map) {
		this.map = map;
	}
}
